package cn.memorynine.consumer.service;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.memorynine.common.enums.ResultEnum;
import cn.memorynine.common.model.PageParamModel;
import cn.memorynine.common.tool.CommonTool;
import cn.memorynine.consumer.mapper.ShopMapper;
import cn.memorynine.consumer.model.shop.consumer.*;
import cn.memorynine.consumer.model.shop.manage.CatagoryListItem;
import cn.memorynine.consumer.model.shop.manage.CatagoryListResult;
import cn.memorynine.dao.entity.*;
import cn.memorynine.dao.mapper.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import cn.memorynine.common.model.ResponseWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
* 用户前台-商城服务
* @author 代码生成器
*/
@Slf4j
@Service
public class ShopService {
    @Autowired
    private ShopCommodityMapper shopCommodityMapper;

    @Autowired
    private ShopCommodityCatagoryMapper shopCommodityCatagoryMapper;

    @Autowired
    private ShopCartMapper shopCartMapper;

    @Autowired
    private ShopCartCommodityRelationMapper shopCartCommodityRelationMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ShopAddressMapper shopAddressMapper;

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private ShopOrderItemMapper shopOrderItemMapper;

    @Autowired
    private ConsumerMapper consumerMapper;

    private Snowflake snowflake = IdUtil.getSnowflake(1,1);

    /**
     * 1.获取商品列表
     * @return
     */
    public ResponseWrapper commodityList(CommodityListParam param){
        CommodityListResult commodityListResult = new CommodityListResult();

        //2.准备分页参数
        Page<ShopCommodity> pageInfo = new Page<>(param.getPageNum(), param.getNum(),false);

        List<ShopCommodity> shopCommodities;

        //3.获取商品列表
        Integer typeId = param.getTypeId();
        String searchKey = param.getSearchKey();
        if (typeId == -1){
            //3.1类别全查
            //获取商品总数
            commodityListResult.setTotalNum(shopCommodityMapper.selectCount(
                    Wrappers.<ShopCommodity>lambdaQuery()
                            .like(ShopCommodity::getName, searchKey)
                            .eq(ShopCommodity::getStateId,10)
            ));
            Page<ShopCommodity> shopCommodityPage = shopCommodityMapper.selectPage(pageInfo,
                    Wrappers.<ShopCommodity>lambdaQuery()
                            .like(ShopCommodity::getName, searchKey)
                            .orderByAsc(ShopCommodity::getStateId)
                            .eq(ShopCommodity::getStateId,10)
            );
            shopCommodities = shopCommodityPage.getRecords();
        }else {
            //3.2指定类别查询
            param.setSearchKey("%" + param.getSearchKey() + "%");
            Integer pageNum = (param.getPageNum() - 1) * param.getNum();
            param.setPageNum(pageNum);
            commodityListResult.setTotalNum(shopMapper.CountCommodityListByCatagory(param));
            List<Map<String,Object>> commodityList = shopMapper.CommodityListByCatagory(param);

            shopCommodities = CommonTool.mapListToBeanList(commodityList, ShopCommodity.class);
        }
        List<CommodityList> commodityLists = new ArrayList<>();
        shopCommodities.forEach(commodity->{
            CommodityList commodityList = new CommodityList();
            BeanUtil.copyProperties(commodity,commodityList);
            commodityLists.add(commodityList);
        });

        commodityListResult.setCommodityList(commodityLists);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(commodityListResult);
    }

    /**
     * 2.商品详情
     * @return
     */
    public ResponseWrapper commodityInfo(CommodityInfoParam param){

        CommodityInfoResult commodityInfoResult = new CommodityInfoResult();
        List<ShopCommodity> shopCommodities = shopCommodityMapper.selectList(
                Wrappers.<ShopCommodity>lambdaQuery()
                        .eq(ShopCommodity::getAid, param.getAid())
        );

        if (!shopCommodities.isEmpty()){
            //查询商品基本信息
            ShopCommodity shopCommodity = shopCommodities.get(0);
            BeanUtil.copyProperties(shopCommodity,commodityInfoResult);
            //查询商品的类别信息
            List<Map<String, Object>> maps = shopMapper.CatagoryListByCommodityWithChoose(shopCommodity.getAid());
            List<CatagoryList> catagoryLists = CommonTool.mapListToBeanList(maps, CatagoryList.class);
            commodityInfoResult.setCatagoryList(catagoryLists);
            //查询商品评论信息
            List<Map<String, Object>> commentList = shopMapper.CommentList(shopCommodity.getAid());
            List<CommentList> commentLists = CommonTool.mapListToBeanList(commentList, CommentList.class);
            commodityInfoResult.setCommentList(commentLists);
        }

        //最后一步，返回结果
        return ResponseWrapper.markSuccess(commodityInfoResult);
    }

    /**
     * 3.商品加入购物车
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper addToCart(AddToCartParam param){

        //获得用户的购物车的aid
        List<ShopCart> shopCarts = shopCartMapper.selectList(
                Wrappers.<ShopCart>lambdaQuery()
                        .eq(ShopCart::getConsumerAid, param.getTokenConsumerAid())
        );
        /**
         * 记得删，这里是没用的代码
         */
        if (shopCarts.isEmpty()){
            //用户没购物车就给他创建一个购物车
            ShopCart shopCart = new ShopCart();
            shopCart.setConsumerAid(param.getTokenConsumerAid());
            shopCartMapper.insert(shopCart);
            shopCarts = shopCartMapper.selectList(
                    Wrappers.<ShopCart>lambdaQuery()
                            .eq(ShopCart::getConsumerAid, param.getTokenConsumerAid())
            );
        }

        if (!shopCarts.isEmpty()){
            ShopCart shopCart = shopCarts.get(0);
            //查出这个购物车里的商品列表
            List<ShopCartCommodityRelation> shopCartCommodityRelations = shopCartCommodityRelationMapper.selectList(
                    Wrappers.<ShopCartCommodityRelation>lambdaQuery()
                            .eq(ShopCartCommodityRelation::getShopCartAid, shopCart.getAid())
            );

            //遍历购物车中的商品
            Boolean exist = false;
            for(ShopCartCommodityRelation cartItem : shopCartCommodityRelations){
                //如果购物车里面已经有这件商品了，则原数量加上现在的数量
                if (param.getAid().equals(cartItem.getShopCommodityAid())){
                    //修改这个的数量
                    cartItem.setNum(cartItem.getNum()+ param.getNum());
                    //更新数据
                    shopCartCommodityRelationMapper.updateById(cartItem);
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                //如果购物车里没有这件商品，则插入这条数据
                ShopCartCommodityRelation shopCartCommodityRelation = new ShopCartCommodityRelation();
                shopCartCommodityRelation.setShopCartAid(shopCart.getAid());
                shopCartCommodityRelation.setShopCommodityAid(param.getAid());
                shopCartCommodityRelation.setNum(param.getNum());
                shopCartCommodityRelationMapper.insert(shopCartCommodityRelation);
            }
        }

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 4.提交订单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper submitOrder(SubmitOrderParam param){

        //1.先扣除商品库存，如果不够则不允许购买
        //总款计数
        Integer totalPrice = 0;

        List<ShopOrderItem> shopOrderItemList = new ArrayList<>();
        for(OrderItemList item : param.getOrderItemList()){
            if (item.getAid() != -1){
                //是购物车里的，把购物车项删除
                shopCartCommodityRelationMapper.deleteById(item.getAid());
            }
            ShopOrderItem shopOrderItem = new ShopOrderItem();
            shopOrderItem.setCommondityAid(item.getCommodityAid());
            //获取当前商品信息
            ShopCommodity shopCommodity = shopCommodityMapper.selectList(
                    Wrappers.<ShopCommodity>lambdaQuery()
                            .eq(ShopCommodity::getAid, shopOrderItem.getCommondityAid())
            ).get(0);
            shopOrderItem.setNumber(item.getCommodityNum());
            //判断库存够不够
            if (shopCommodity.getQuantity() < shopOrderItem.getNumber()){
                //库存不够
                try {
                    throw new Exception();
                } catch (Exception e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
                return ResponseWrapper.markError(ResultEnum.Commodity_Quantity_Not_Enough);
            }
            shopCommodity.setSale(shopCommodity.getSale()+1);
            shopCommodity.setQuantity(shopCommodity.getQuantity()-1);
            shopCommodityMapper.updateById(shopCommodity);

            shopOrderItem.setName(shopCommodity.getName());
            shopOrderItem.setImage(shopCommodity.getImage());
            shopOrderItem.setPoints(shopCommodity.getPrice());

            totalPrice += shopOrderItem.getPoints() * shopOrderItem.getNumber();
            shopOrderItemList.add(shopOrderItem);
        }

        //2.创建订单
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setCustomerAid(param.getTokenConsumerAid());
        shopOrder.setNumber(snowflake.nextIdStr());
        ShopAddress shopAddress = shopAddressMapper.selectList(
                Wrappers.<ShopAddress>lambdaQuery().eq(ShopAddress::getAid, param.getAddressAid())
        ).get(0);
        String address = shopAddress.getName() +" "+shopAddress.getPhone()
                +" "+shopAddress.getProvince()+" "+shopAddress.getCity()
                +" "+shopAddress.getDetailAddress();
        shopOrder.setAddress(address);
        //状态设置为待付款
        shopOrder.setStateId(10);

        shopOrder.setSumPoints(totalPrice);

        shopOrderMapper.insert(shopOrder);
        for (ShopOrderItem shopOrderItem : shopOrderItemList) {
            log.error(shopOrderItem.toString());
            shopOrderItem.setOrderAid(shopOrder.getAid());
            shopOrderItemMapper.insert(shopOrderItem);
        }

        //至此，订单和订单项更新完毕

        SubmitOrderResult submitOrderResult = new SubmitOrderResult();
        submitOrderResult.setOrderAid(shopOrder.getAid());
        //最后一步，返回结果
        return ResponseWrapper.markSuccess(submitOrderResult);
    }

    /**
     * 5.订单付款
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper payForOrder(PayForOrderParam param){
        Consumer consumer = consumerMapper.selectList(
                Wrappers.<Consumer>lambdaQuery().eq(Consumer::getAid,param.getTokenConsumerAid())
        ).get(0);

        List<ShopOrder> shopOrders = shopOrderMapper.selectList(
                Wrappers.<ShopOrder>lambdaQuery()
                        .eq(ShopOrder::getAid, param.getAid())
        );

        if (!shopOrders.isEmpty()){
            ShopOrder shopOrder = shopOrders.get(0);
            //判断用户积分够不够
            if (shopOrder.getSumPoints() > consumer.getPoints()){
                //积分不够
                try {
                    throw new Exception();
                } catch (Exception e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
                return ResponseWrapper.markError(ResultEnum.Points_Not_Enough);
            } else {
                //积分足够
                //扣除用户积分
                consumer.setPoints(consumer.getPoints()-shopOrder.getSumPoints());
                consumerMapper.updateById(consumer);
                //设置订单状态为待发货
                shopOrder.setStateId(20);
                shopOrder.setTimePayment(LocalDateTime.now());
                shopOrderMapper.updateById(shopOrder);
            }
        }

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 6.订单收货
     * @return
     */
    public ResponseWrapper receiveOrder(ReceiveOrderParam param){
        ShopOrder shopOrder = new ShopOrder();
        //状态设置为已完成
        shopOrder.setStateId(50);
        shopOrder.setAid(param.getAid());
        shopOrder.setTimeOrderFinish(LocalDateTime.now());
        shopOrderMapper.updateById(shopOrder);

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 7.评论商品
     * @return
     */
    public ResponseWrapper postComment(PostCommentParam param){
        //TODO 请在此处编写业务逻辑

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 8.取消订单
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper delOrder(DelOrderParam param){

        List<Consumer> consumers = consumerMapper.selectList(
                Wrappers.<Consumer>lambdaQuery().eq(Consumer::getAid, param.getTokenConsumerAid())
        );
        if (!consumers.isEmpty()){
            Consumer consumer = consumers.get(0);
            List<ShopOrder> shopOrders = shopOrderMapper.selectList(
                    Wrappers.<ShopOrder>lambdaQuery().eq(ShopOrder::getAid, param.getAid())
            );
            if (!shopOrders.isEmpty()){
                ShopOrder shopOrder = shopOrders.get(0);
                //取消订单只能在未发货的时候取消订单
                if (shopOrder.getStateId() <= 20){
                    //获取订单下的订单项列表
                    List<ShopOrderItem> shopOrderItemList = shopOrderItemMapper.selectList(
                            Wrappers.<ShopOrderItem>lambdaQuery()
                                    .eq(ShopOrderItem::getOrderAid, shopOrder.getAid())
                    );
                    //恢复商品的库存和销量
                    for (ShopOrderItem shopOrderItem : shopOrderItemList) {
                        ShopCommodity shopCommodity = shopCommodityMapper.selectOne(
                                Wrappers.<ShopCommodity>lambdaQuery()
                                        .eq(ShopCommodity::getAid, shopOrderItem.getCommondityAid())
                        );
                        shopCommodity.setQuantity(shopCommodity.getQuantity()+shopOrderItem.getNumber());
                        shopCommodity.setSale(shopCommodity.getSale()-shopOrderItem.getNumber());
                        shopCommodityMapper.updateById(shopCommodity);
                    }
                    if (shopOrder.getStateId() == 10){
                        //未付款
                    } else if (shopOrder.getStateId() == 20){
                        //已付款
                        log.error("???????");
                        //退还用户积分
                        consumer.setPoints(consumer.getPoints()+shopOrder.getSumPoints());
                        consumerMapper.updateById(consumer);
                    }
                    //置订单为取消状态
                    shopOrder.setStateId(60);
                    shopOrderMapper.updateById(shopOrder);
                }
            }
        }

        //最后一步，返回结果
        return ResponseWrapper.markSuccess();
    }

    /**
     * 9.获取用户地址列表
     * @return
     */
    public ResponseWrapper addressList(AddressListParam param) {
        List<AddressListResult> addressListResults = new ArrayList<>();
        //先查询出默认的地址
        List<ShopAddress> defaultShopAddresses = shopAddressMapper.selectList(
                Wrappers.<ShopAddress>lambdaQuery()
                        .eq(ShopAddress::getConsumerAid, param.getTokenConsumerAid())
                        .eq(ShopAddress::getIsDefault,true)
                        .eq(ShopAddress::getIsDelete,false)
        );
        if (!defaultShopAddresses.isEmpty()){
            ShopAddress shopAddress = defaultShopAddresses.get(0);
            AddressListResult addressListResult = new AddressListResult();
            BeanUtil.copyProperties(shopAddress,addressListResult);
            addressListResults.add(addressListResult);
        }
        //再查非默认的地址
        List<ShopAddress> shopAddresses = shopAddressMapper.selectList(
                Wrappers.<ShopAddress>lambdaQuery()
                        .eq(ShopAddress::getConsumerAid, param.getTokenConsumerAid())
                        .eq(ShopAddress::getIsDefault,false)
                        .eq(ShopAddress::getIsDelete,false)
        );
        shopAddresses.forEach(item->{
            AddressListResult addressListResult = new AddressListResult();
            BeanUtil.copyProperties(item,addressListResult);
            addressListResults.add(addressListResult);
        });

        return ResponseWrapper.markSuccess(addressListResults);
    }

    /**
     * 10.获取商品分类列表
     */
    public ResponseWrapper categoryList(CategoryListParam param) {
        List<CategoryListResult> catagoryListResults = new ArrayList<>();
        catagoryListResults.add(new CategoryListResult(-1,"全部类别"));
        List<ShopCommodityCatagory> shopCommodityCatagories = shopCommodityCatagoryMapper.selectList(
                Wrappers.<ShopCommodityCatagory>lambdaQuery()
                        .orderByAsc(ShopCommodityCatagory::getIsDelete)
        );
        shopCommodityCatagories.forEach(catagory->{
            CategoryListResult catagoryListResult = new CategoryListResult();
            BeanUtil.copyProperties(catagory,catagoryListResult);
            catagoryListResults.add(catagoryListResult);
        });
        return ResponseWrapper.markSuccess(catagoryListResults);
    }

}